if (!caryr) {
    caryr = {};
}
/*********************ErpG used****************/
caryr.dataTable = {
    table: {},
    datatable_draw: '',
    onViewEvent: {},
    onInlineSave: {},
    create: function (option) {
        var that = this;
        this.tableId = option.tableId;
        var columns ;

        if (option.disableCheckbox) {
            columns = option.columns;
        } else {
            columns = [{
                orderable: false,
                className: 'table_check_td',
                render: function (data, type, full, meta) {
                    var div = '';
                    div = '' +
                        '<th class="center">' +
                        '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">' +
                        '<input type="checkbox" class="group-checkable"/>' +
                        '<span></span>' +
                        '</label>' +
                        '</th>';
                    return div;
                }
            }].concat(option.columns);
        }

        if(!option.disableView){
            columns = columns.concat([{
                data: "id",
                orderable: false,
                render: function (e, n) {
                    var div =
                        '<div class="visible-xs visible-md visible-lg action-buttons">' +
                        '<a class="blue view_entity_btn" href="#"  data-action > <i class="fa fa-search-plus"></i> </a>' +
                        '</div>';
                    if (option.enableInlineEdit) {
                        div =
                            '<div class="visible-xs visible-md visible-lg action-buttons">' +
                            '<a class="blue inline_edit_btn" href="javascript:;"  data-action > <i class="fas fa-pencil-alt"></i> </a>' +
                            '<a class="font-green inline_save_btn hidden " href="javascript:;"  data-action > <i class="fas fa-check"></i> </a>' +
                            '<a class="font-red inline_cancel_btn hidden " href="javascript:;"  data-action > <i class="fas fa-times"></i> </a>' +
                            '</div>'
                    }
                    return div;
                },
                className: "align-right all"
            }]);
        }

        this.onViewEvent = option.onViewEvent;
        this.onInlineSave = option.onInlineSave;

        var pageLength = 25;
        if(option.pageLength){
            pageLength = option.pageLength;
        }
        var defaultOrderByDir = option.defaultOrderByDir?option.defaultOrderByDir:"desc";
        var table = $(option.tableId).DataTable({
            language: {
                "url": "resources/bundle/dataTable_" + option.lang + ".json"
            },
            ajax: {
                "url": option.url
            },
            processing: true,
            searching: true,
            serverSide: true,
            buttons: [],
            responsive: {	// setup responsive extension: http://datatables.net/extensions/responsive/
                details: {}
            },
            lengthMenu: [
                [10, 25, 50, 100, -1],
                [10, 25, 50, 100, "All"] // change per page values here
            ],
            pageLength: pageLength,
            order: [[option.defaultOrderBy, defaultOrderByDir]],
            columns: columns,
            dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
        }).on('preXhr.dt', function (e, settings, data) {
            this.datatable_draw = data.draw;
            data.size = data.length;
            data.current = data.start / data.length + 1;
            //OrderBy
            var order = data.order[0];
            data.orderBy = data.columns[order.column].data;
            data.isAsc = order.dir == "asc" ? true : false;
        }).on('xhr.dt', function (e, settings, json, xhr) {
            if(json){
                json.draw = this.datatable_draw;
                //TODO: total records
                json.recordsTotal = json.size;
                json.recordsFiltered = json.size;
            }
        }).on('draw.dt', function () {
            $('table th input:checkbox').attr('checked', false);
            that.attachSelectAll(option);
            that.attachSelectCheck(option);
            that.attachViewBtn(option.tableId);
            that.attachInlineSave(option.tableId);

            if (option.enableInlineEdit) {
                $('.inline_edit_btn').on('click',function(){
                    var row = $(this).closest('tr[role="row"]');
                    row.find('.inline_edit_btn').addClass("hidden");
                    row.find('.inline_save_btn').removeClass("hidden");
                    row.find('.inline_cancel_btn').removeClass("hidden");

                    row.find('.inline_display').addClass("hidden");
                    row.find('.inline_input').removeClass("hidden");
                    row.find('.inline_input').focus();
                });
                $('.inline_save_btn, .inline_cancel_btn').on('click',function(){
                    var row = $(this).closest('tr[role="row"]');
                    row.find('.inline_edit_btn').removeClass("hidden");
                    row.find('.inline_save_btn').addClass("hidden");
                    row.find('.inline_cancel_btn').addClass("hidden");

                    row.find('.inline_display').removeClass("hidden");
                    row.find('.inline_input').addClass("hidden");
                });
            }
            if (option.draw) {
                option.draw();
            }
            that.updateTableI18N();
        }).on('init.dt', function () {
            $('.dataTables_filter').addClass("hidden");	//hide dataTable search
            caryr.loadI18n();
        });

        $(option.tableId).closest('.datatable-portlet').find('#btn_refresh_dt').on("click", function () { //attach table refresh
            table.draw();
        });

        //attach delete button
        $(option.tableId).closest('.datatable-portlet').find('#btn_del_entity').on("click", function () {
            var ids = caryr.dataTable.selectedIds(table);
            if (!ids) {
                return;
            }
            caryr.deleteEntity({
                ids: ids,
                url: option.url,
                success: function () {
                    table.draw();
                },
                error: function () {
                    table.draw();
                }
            });
        });

        this.table = table;
        return this.table;
    },
    selectedData: function(table){
        return table.rows('.selected').data();
    },
    selectedIds: function (table,option) {
        //check selected row
        var selectData = caryr.dataTable.selectedData(table);
        var emptyCheck = option && option.emptyCheck == false ? false : true;
        if (emptyCheck && selectData.length == 0) {
            swal($.i18n.prop("msg_com_noDataSelect"), "", "error");
            return;
        }
        //collect selected Id
        var ids = new Array();
        selectData.each(function (e, i) {
            ids.push(e.id);
        });
        return ids;
    },
    attachSelectAll: function (option) {
        $('table th input:checkbox').off('click').on('click', function () {
            var that = this;
            $(this).closest('table').find('tr > td:first-child input:checkbox').each(function () {
                this.checked = that.checked;
                if(this.checked){
                    $(this).closest('tr').addClass('selected');
                }else{
                    $(this).closest('tr').removeClass('selected');
                }
            });

            if(option.checkAllEvent){
                option.checkAllEvent();
            }
        })
    },
    attachSelectCheck: function (option) {
        $(option.tableId).find('tr > td:first-child input:checkbox').each(function (i, e) {
            $(e).on("click", function () {
                $(this).closest('tr').toggleClass('selected');
                if(option.checkEvent){
                    option.checkEvent();
                }
            })
        });
    },
    attachInlineSave: function (tableId) {
        var that = this;
        $(tableId).find('.inline_save_btn').each(function (i, e) {
            $(e).on("click", function () {
                var tr = $(this).closest('tr');
                var data = that.table.row(tr).data();
                that.onInlineSave(data, this);
            })
        });
    },
    attachViewBtn: function (tableId) {
        var that = this;
        $(tableId).find('.view_entity_btn').each(function (i, e) {
            $(e).on("click", function () {
                var tr = $(this).closest('tr');
                var data = that.table.row(tr).data();
                that.onViewEvent(data);
            })
        });
    },
    updateTableI18N: function () {
        $(this.tableId).find('td>span').each(function (i, e) {
            var msgCls = $(e).attr('class');
            if (msgCls.indexOf('msg_') != -1) {
                $(e).text($.i18n.prop(msgCls.match(/msg_.*/)[0]));
            }
        });
    }
};